import { ChangeDetectionStrategy, Component, DestroyRef } from '@angular/core';
import { FormControl, FormGroup, NonNullableFormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';

import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzSelectModule } from 'ng-zorro-antd/select';

import { LoginApi } from '../service/login.api';
import { LoginDto, LoginSuccessDto, UserInfo } from '../interfaces/login-dto';
import { Router } from '@angular/router';
import { UserInfoService } from '../service/store/userinfo.service';
// import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [ReactiveFormsModule, NzFormModule, NzInputModule, NzButtonModule, NzCheckboxModule, NzSelectModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.less',
  // changeDetection: ChangeDetectionStrategy.OnPush, // 只在 @Input 数据发生变化时才会重新渲染，可以配合 cdr 强制渲染
  changeDetection: ChangeDetectionStrategy.Default, // 默认值，变量双向绑定
})
export class LoginComponent {

  hospList: any[] = [];

  private tenantId = '0001';

  constructor(
    private fb: NonNullableFormBuilder,
    private loginApi: LoginApi,
    private router: Router,
    private userinfoSerivce: UserInfoService
  ) { }

  validateForm: FormGroup<{
    userName: FormControl<string>;
    password: FormControl<string>;
    remember: FormControl<boolean>;
    hospId: FormControl<string>;
  }> = this.fb.group({
    userName: ['admin', [Validators.required]],
    password: ['123456', [Validators.required]],
    remember: [true],
    hospId: [this.tenantId, [Validators.required]],
  });



  ngOnInit() {
    this.loginApi.getLoginHosp(this.tenantId).subscribe(el => {
      if (el.code === 200) {
        const arr = el.data as any[] ?? [];
        this.hospList = arr.map(one => {
          return {
            hospId: one.hospId,
            hospName: one.hospName
          }
        })
      }
    });
  }

  private storeUserInfo(data: unknown) {
    this.userinfoSerivce.setUserModel(data as UserInfo);
  }

  submitForm(): void {
    console.log('submit', this.validateForm.value);

    const data: LoginDto = {
      password: this.validateForm.value.password ?? '',
      tenantId: this.tenantId,
      hospId: this.validateForm.value.hospId ?? '',
      username: this.validateForm.value.userName ?? '',
      code: '',
      uuid: ''
    }
    this.loginApi.postLogin(data)
      //   .pipe(
      //   // 组件销毁时取消订阅，以免内存泄漏
      //   // HttpClient 的订阅会自行取消，不会有内存泄漏
      //   // takeUntilDestroyed(this.destroyRef)
      // )
      .subscribe(res => {
        if (res.code === 200 && !res.msg) {
          const resp = res.data as LoginSuccessDto;
          localStorage.setItem('jwt', resp.accessToken ?? '');
          localStorage.setItem('userinfo', JSON.stringify(resp.sys_user) ?? '');
          // 将用户数据存到单例类中
          this.storeUserInfo(resp.sys_user);

          this.router.navigateByUrl("/workbench")
        } else {
          alert(res.msg);
        }
      })
  }

} 
